package be.redo.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public abstract class AbstractDAO<T extends Object> {

	private Class<T> entityClass;

	@PersistenceContext
	protected EntityManager em;

	@SuppressWarnings("unchecked")
	private Class<T> getEntityClass() {
		if (entityClass == null) {
			Type type = this.getClass().getGenericSuperclass();
			ParameterizedType parameterizedType = (ParameterizedType) type;
			entityClass = (Class<T>) parameterizedType.getActualTypeArguments()[0];
		}
		return entityClass;
	}

	public T find(Number key) {
		return em.find(getEntityClass(), key);
	}

	public void persist(T entity) {
		this.em.persist(entity);
	}

	public void flush() {
		this.em.flush();
	}

	public T merge(T entity) {
		return this.em.merge(entity);
	}

	public void remove(T entity) {
		this.em.remove(entity);
	}

	/*
	 * public void deleteInBatch(Iterable<T> arg0) { this.em.
	 * 
	 * }
	 */
}
